package com.cosmoplat.xikai.common.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cosmoplat.xikai.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @ClassName MyMetaObjectHandler
 * @Description 创建，新增的拦截器
 * @Author wdf
 * @Date 2025/1/9
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createBy", this::getUserName, String.class);
        this.strictInsertFill(metaObject, "createTime", this::getCurrentDate, Date.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 如果有需要在更新时自动填充的字段，可以在这里实现
        this.strictUpdateFill(metaObject, "updateBy", this::getUserName, String.class);
        this.strictUpdateFill(metaObject, "updateTime", this::getCurrentDate, Date.class);
    }

    private Date getCurrentDate() {
        return new Date(); // 返回当前时间
    }

    public String getUserName() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            log.error("获取用户名失败：{}", e.getMessage());
            return "";
        }
    }
}
